﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

#region using
using System;
using System.Drawing.Imaging;
using System.Configuration;
using System.IO;
using System.Drawing;
using System.ServiceModel;
using System.Text.RegularExpressions;
using NetBay.Core.Encryption;
using Rio.WCF.Services.ExifMetadata;
using iTextSharp.text.pdf;
using NetBay.Core.BusinessEntities;
using NetBay.Core.Extensions;

using Aspose.Cells;
using Aspose.Slides;
//using Aspose.Cells.Rendering;
using Aspose.Slides.Pptx;
using Aspose.Words.Saving;

//using Leadtools.Codecs;
//using Leadtools;

using GdPicture;

using Aspose.Cells.Rendering;
using NetBay.Core.BusinessEntities.Barcodes;
using Rio.WCF.Services.helpers;

#endregion

namespace Rio.WCF.Services
{
    public partial class Treatments
        : IDisposable
    {

        public enum ImageType { Tiff, Bmp, Jpg, Png };
        public bool FillMetadataInImageRio { get; set; }
        public ImageRio ImageRioToFillMetadata { get; set; }
        private bool _isInit = false;
        private GdPictureImaging m_oGdPictureImaging = new GdPictureImaging();
        private GdPicturePDF m_oGdPicturePDF = new GdPicturePDF();

        #region Public method

        /// <summary>
        /// Initializes a new instance of the <see cref="PDFtoImage" /> class.
        /// </summary>
        public Treatments()
        {
            m_oGdPictureImaging = new GdPictureImaging();
            m_oGdPicturePDF = new GdPicturePDF();
            _isInit = false;
            LicenceGdPicture();
        }

        /// <summary>
        /// Set GdPicture Licence  key
        /// </summary>
        public void LicenceGdPicture()
        {
            if (!_isInit)
            {
                m_oGdPictureImaging.SetLicenseNumberUpgrade(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.License.V7"), ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.License.V8")); // Please, replace XXXX by a valid demo or commercial license key. 
                m_oGdPictureImaging.SetLicenseNumber1DBarcodeRecognition(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.License.V8")); // Please, replace XXXX by a valid demo or commercial license key. 
                m_oGdPictureImaging.SetLicenseNumberOCRTesseract(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.License.V8")); // Please, replace XXXX by a valid demo or commercial license key. 
                m_oGdPicturePDF.SetLicenseNumber(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.License.V8"));
                _isInit = true;
            }
        }

        /// <summary>
        /// Checks the application request key.
        /// </summary>
        /// <param name="p_oMessageRequest">The p_o message request.</param>
        public static void CheckApplicationRequestKey(MessageRequest p_oMessageRequest)
        {
            try
            {
                NetBay.Core.Log.LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
                NetBay.Core.Log.LogManager.Instance().LogInfo("CheckApplicationRequestKey()");


                if (p_oMessageRequest == null)
                    throw new FaultException<string>("Invalid license key.");
                string decryptedLicenseKey = AesEncryption.Decrypt(p_oMessageRequest.LicenseKey);

                string[] digits = decryptedLicenseKey.Split('$');
                if (digits.Length == 2)
                {
                    DateTime date = Convert.ToDateTime(digits[1]);
                    if (digits[0].Equals(ConfigurationManager.AppSettings.Get("LicenseKey")) == false)
                        throw new FaultException<string>("Invalid license key.");

                    if (DateTime.Now > Convert.ToDateTime(date))
                        throw new FaultException<string>("Invalid license key.");
                }
                else
                {
                    throw new FaultException<string>("Invalid license key.");
                }

                NetBay.Core.Log.LogManager.Instance().LogInfo("License key validated successfully");
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CheckApplicationRequestKey EXCEPTION: [" + ex.ToString() + "] " + DateTime.Now);
            }
        }

        /// <summary>
        /// Saves to JPEG.
        /// </summary>
        /// <param name="p_sDestinationFullPath">The P_S destination full path.</param>
        /// <param name="p_sOriginalFile">The P_S original file.</param>
        /// <param name="p_iQuality">The p_i quality.</param>
        public void SaveToJpeg(string p_sDestinationFullPath, string p_sOriginalFile, int p_iQuality)
        {
            int m_iImageID = 0;
            GdPictureStatus status;
            try
            {
                NetBay.Core.Log.LogManager.Instance().LogInfo("------------- start of SaveToJpeg " + DateTime.Now);

                m_iImageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(p_sOriginalFile);

                status = m_oGdPictureImaging.SaveAsJPEG(m_iImageID, p_sDestinationFullPath, p_iQuality);
                NetBay.Core.Log.LogManager.Instance().LogDebug("SaveAsJPEG status:" + status.ToString());
                
                NetBay.Core.Log.LogManager.Instance().LogInfo("------------- end of SaveToJpeg " + DateTime.Now);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN SaveToJpeg EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (m_iImageID > 0)
                    m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
            }
        }

        /// <summary>
        /// Saves the tiff as JPEG.
        /// </summary>
        /// <param name="p_sOriginalFile">The original file.</param>
        /// <param name="p_sDestinationFullPath">The destination full path.</param>
        /// <param name="p_iStartPage">The start page.</param>
        public void SaveTiffAsJpeg(string p_sOriginalFile, string p_sDestinationFullPath, int p_iStartPage)
        {
            int m_iImageID = 0 ;
            GdPictureStatus status;
            try
            {
                NetBay.Core.Log.LogManager.Instance().LogInfo("------------- start of SaveTiffAsJpeg " + DateTime.Now);

                m_iImageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(p_sOriginalFile);

                status = m_oGdPictureImaging.TiffSelectPage(m_iImageID, p_iStartPage);
                NetBay.Core.Log.LogManager.Instance().LogDebug("TiffSelectPage status:" + status.ToString());

                status = m_oGdPictureImaging.SaveAsJPEG(m_iImageID, p_sDestinationFullPath);
                NetBay.Core.Log.LogManager.Instance().LogDebug("SaveAsJPEG status:" + status.ToString());

                int m_iHeigth = m_oGdPictureImaging.GetHeight(m_iImageID);
                int m_iWidth = m_oGdPictureImaging.GetWidth(m_iImageID);

                var l_oSize = GetSizeImage(m_iWidth, m_iHeigth, int.Parse(ConfigurationManager.AppSettings.Get("MaxWidthResize")));
                if (m_iHeigth > l_oSize.Height || m_iWidth > l_oSize.Width)
                {
                    Treatments.ResizeImage(
                        p_sDestinationFullPath,
                        p_sDestinationFullPath,
                        l_oSize.Width,
                        l_oSize.Height,
                        true
                        );
                }
                NetBay.Core.Log.LogManager.Instance().LogInfo("------------- end of SaveTiffAsJpeg " + DateTime.Now);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN SaveTiffAsJpeg EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
                throw new Exception(ex.Message);
            }
            finally
            {
                if(m_iImageID> 0)
                    m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
            }
        }

        /// <summary>
        /// Return the ImageCodecInfo corresponding
        /// </summary>
        /// <param name="p_sMimeType">String describer of the ImageCodecInfo</param>
        /// <returns>The appropriate ImageCodecInfo</returns>
        public static ImageCodecInfo GetEncoderInfo(string p_sMimeType)
        {
            var l_oEncoders = ImageCodecInfo.GetImageEncoders();
            for (var j = 0; j < l_oEncoders.Length; j++)
            {
                if (l_oEncoders[j].MimeType == p_sMimeType)
                    return l_oEncoders[j];
            }
            return null;
        }



        //public static


        /// <summary>
        /// Extract a specific page of a pdf document
        /// </summary>
        /// <param name="p_oPdfReader">Full path of the source document</param>
        /// <param name="p_iPageNumberToExtract">the page to extract</param>
        /// <param name="l_sOutPdfFileFullPath">Full path of the output pdf file</param>
        /// <param name="p_sOriginalFileNameFullPath"></param>
        public static void ExtractPdfPage(PdfReader p_oPdfReader, int p_iPageNumberToExtract, string l_sOutPdfFileFullPath, string p_sOriginalFileNameFullPath)
        {
            FileStream l_oFileStream = null;
            try
            {
                NetBay.Core.Log.LogManager.Instance().LogInfo(
                    "ExtractPdfPage--------------------------------- ExtractPdfPage p_iPageNumberToExtract[" + p_iPageNumberToExtract +
                    "] l_sOutPdfFileFullPath [" + l_sOutPdfFileFullPath + "]--------------------------- ");

                var l_oDocument = new iTextSharp.text.Document(p_oPdfReader.GetPageSizeWithRotation(1));
                l_oFileStream = new FileStream(l_sOutPdfFileFullPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                var l_oPdfCpy = new PdfCopy(l_oDocument, l_oFileStream);
                l_oDocument.Open();
                var l_oPage = l_oPdfCpy.GetImportedPage(p_oPdfReader, p_iPageNumberToExtract);
                l_oPdfCpy.AddPage(l_oPage);
                l_oDocument.Close();
                NetBay.Core.Log.LogManager.Instance().LogInfo("ExtractPdfPage--------------------------------- ExtractPdfPage finished -----------------------");

            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogInfo("ExtractPdfPage Exception ---------[" + ex.Message + "]-----------------------");
                if (l_oFileStream != null)
                {
                    l_oFileStream.Close();
                    l_oFileStream.Dispose();
                }
                throw;
            }
        }

        /// <summary>
        /// Perform actions for a specified file
        /// </summary>
        /// <param name="p_sOriginalFileFullPath">The full path of the original file</param>
        /// <param name="p_sThumbNailFileFullPath">The full path of the thumbnail</param>
        public void CreateThumb(string p_sOriginalFileFullPath, string p_sThumbNailFileFullPath)
        {
            try
            {
                NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreateThumb ------------------------------------------------ " + DateTime.Now);
                NetBay.Core.Log.LogManager.Instance().LogInfo("------------------------ p_sOutPutFileFullPath [" + p_sThumbNailFileFullPath + "] --------------------------- ");
                NetBay.Core.Log.LogManager.Instance().LogInfo("------------------------ New File p_sFullPath[" + p_sOriginalFileFullPath + "] --------------------------- ");

                FileInfo l_oSourceFileInfo;
                CheckDirectory(new FileInfo(p_sThumbNailFileFullPath).DirectoryName);

                try
                {
                    l_oSourceFileInfo = new FileInfo(p_sOriginalFileFullPath);

                    try
                    {
                        if (FillMetadataInImageRio)
                        {
                            ImageRio tempImageRio = ImageRioToFillMetadata;

                            FillMetadata(new FileInfo(p_sOriginalFileFullPath), ref tempImageRio);

                            ImageRioToFillMetadata = tempImageRio;

                            NetBay.Core.Log.LogManager.Instance().LogInfo("--------------------------------- Common Metadata Extracted --------------------------- " + DateTime.Now);
                        }
                    }
                    catch (Exception ex)
                    {
                        NetBay.Core.Log.LogManager.Instance().LogError("--------------------------------- Exception in Extraction of Common Metadata[" + ex.Message + "] --------------------------- " + DateTime.Now);
                    }

                    if (l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.BMP.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.JPEG.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.JPG.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.TIF.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.TIFF.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.PNG.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.GIF.szGetDescription())
                        )
                    {
                        CreateImageThumbNail(l_oSourceFileInfo, p_sThumbNailFileFullPath);
                    }
                    else if (l_oSourceFileInfo.Extension.ToLower().Equals(Constant.VideoFileFormat.AVI.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.VideoFileFormat.WMV.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.VideoFileFormat.MPEG.szGetDescription())
                        )
                    {
                        CreateVideoThumbNail(p_sThumbNailFileFullPath);
                    }
                    else if (l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.PDF.szGetDescription())
                        )
                    {
                        CreatePdfThumbNail(l_oSourceFileInfo, p_sThumbNailFileFullPath);
                    }
                    else if (l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.XLS.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.XLSX.szGetDescription())
                        )
                    {
                        CreateExcelThumbNail(l_oSourceFileInfo, p_sThumbNailFileFullPath);
                    }
                    else if (l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.DOC.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.DOCX.szGetDescription())
                        || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.RTF.szGetDescription())
                        )
                    {
                        CreateWordThumbNail(l_oSourceFileInfo, p_sThumbNailFileFullPath);
                    }
                    else if (l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.PPT.szGetDescription())
                        )
                    {
                        CreatePowerPointThumbNail(l_oSourceFileInfo, p_sThumbNailFileFullPath);
                    }
                    else if (l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.PPTX.szGetDescription())
                        )
                    {
                        CreatePowerPointXThumbNail(l_oSourceFileInfo, p_sThumbNailFileFullPath);
                    }
                    else if (( l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.TXT.szGetDescription()) ))
                    {
                        CreateTxtThumbNail(p_sThumbNailFileFullPath);
                    }
                    else if ((l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.ZIP.szGetDescription())))
                    {
                        CreateMiscFileThumbNail(p_sThumbNailFileFullPath, Constant.DocumentFileFormat.ZIP.ToString());
                    }
                    else
                    {
                        CreateMiscFileThumbNail(p_sThumbNailFileFullPath);
                    }
                }
                catch (Exception ex)
                {
                    NetBay.Core.Log.LogManager.Instance().LogError("--------------------------------- Exception in CreateThumb[" + ex.Message + "] --------------------------- " + DateTime.Now);
                }
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CreateThumb EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }

            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreateThumb ------------------------------------------------ " + DateTime.Now);
        }

        /// <summary>
        /// Allow to resize an image
        /// </summary>
        /// <param name="p_sOriginalFileFullPath"></param>
        /// <param name="p_sNewFilefullPath"></param>
        /// <param name="p_iNewWidth"></param>
        /// <param name="p_iMaxHeight"></param>
        /// <param name="p_bOnlyResizeIfWider"></param>
        public static void ResizeImage(string p_sOriginalFileFullPath, string p_sNewFilefullPath, int p_iNewWidth, int p_iMaxHeight, bool p_bOnlyResizeIfWider)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            NetBay.Core.Log.LogManager.Instance().LogInfo("---------------------------Call of ResizeImage");


            GdPictureImaging m_oGdPictureImaging = new GdPictureImaging();
            int m_iImageID = 0;
            try
            {
                m_iImageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(p_sOriginalFileFullPath);
                int imageWidth = m_oGdPictureImaging.GetWidth(m_iImageID);
                int imageHeight = m_oGdPictureImaging.GetHeight(m_iImageID);

                if (p_bOnlyResizeIfWider)
                {
                    if (imageWidth <= p_iNewWidth)
                    {
                        p_iNewWidth = imageWidth;
                    }
                }

                var l_iNewHeight = imageHeight * p_iNewWidth / imageWidth;
                if (l_iNewHeight > p_iMaxHeight)
                {
                    // Resize with height instead
                    p_iNewWidth = imageWidth * p_iMaxHeight / imageHeight;
                    l_iNewHeight = p_iMaxHeight;
                }

                //Resize and save the image
                m_oGdPictureImaging.Resize(m_iImageID, p_iNewWidth, l_iNewHeight, System.Drawing.Drawing2D.InterpolationMode.Default);
                NetBay.Core.BusinessEntities.Constant.ImageFileFormat result = Utils.ConvertFileNameToFileFormat(p_sNewFilefullPath);
                switch (result)
	            {
		            case Constant.ImageFileFormat.BMP:
                        m_oGdPictureImaging.SaveAsBMP(m_iImageID, p_sNewFilefullPath);
                        break;
                    case Constant.ImageFileFormat.GIF:
                        m_oGdPictureImaging.SaveAsGIF(m_iImageID, p_sNewFilefullPath);
                        break;
                    case Constant.ImageFileFormat.JPEG:
                    case Constant.ImageFileFormat.JPG:
                        m_oGdPictureImaging.SaveAsJPEG(m_iImageID, p_sNewFilefullPath);
                        break;
                    case Constant.ImageFileFormat.PNG:
                        m_oGdPictureImaging.SaveAsPNG(m_iImageID, p_sNewFilefullPath);
                        break;
                    case Constant.ImageFileFormat.TIF:
                    case Constant.ImageFileFormat.TIFF:
                        m_oGdPictureImaging.SaveAsTIFF(m_iImageID, p_sNewFilefullPath, m_oGdPictureImaging.GetTiffCompression(m_iImageID));
                        break;
	            }
            }
            catch (Exception ex)
            {

                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN ResizeImage EXCEPTION: [" + ex.ToString() + "] " + DateTime.Now);
            }
            finally
            {
                m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
            }

            NetBay.Core.Log.LogManager.Instance().LogInfo("---------------------------End of Call of ResizeImage");
        }

        /// <summary>
        /// Fills the metadata.
        /// </summary>
        /// <param name="p_oDocumentFileInfo">The p_o document file info.</param>
        /// <param name="p_oImageRioToFillMetadata">The p_o image rio to fill metadata.</param>
        public static void FillMetadata(FileInfo p_oDocumentFileInfo, ref ImageRio p_oImageRioToFillMetadata, bool fullMetaData = false)
        {
            /*
             * Common Metadata
             */

            p_oImageRioToFillMetadata.CreationDate = p_oDocumentFileInfo.CreationTime;
            p_oImageRioToFillMetadata.LastModificationDate = p_oDocumentFileInfo.LastWriteTime;
            p_oImageRioToFillMetadata.ImageSize = p_oDocumentFileInfo.Length;

            /* 
             * Image Metadata
             */
            if (fullMetaData)
            {
                if (p_oDocumentFileInfo.Extension.ToLowerInvariant() == Constant.ImageFileFormat.JPEG.szGetDescription()
                    || p_oDocumentFileInfo.Extension.ToLowerInvariant() == Constant.ImageFileFormat.JPG.szGetDescription()
                    || p_oDocumentFileInfo.Extension.ToLowerInvariant() == Constant.ImageFileFormat.TIF.szGetDescription()
                    || p_oDocumentFileInfo.Extension.ToLowerInvariant() == Constant.ImageFileFormat.TIFF.szGetDescription())
                {
                    try
                    {
                        ExifTagCollection exifTagCollection = new ExifTagCollection(p_oDocumentFileInfo.FullName);
                        p_oImageRioToFillMetadata.Author = exifTagCollection[0x13B].Value;
                    }
                    catch
                    {
                    }

                    using (Image image = Image.FromFile(p_oDocumentFileInfo.FullName))
                    {
                        try
                        {
                            p_oImageRioToFillMetadata.Dimension = String.Format("{0} x {1}", image.Size.Width, image.Size.Height);
                        }
                        catch
                        {
                        }
                        try
                        {
                            p_oImageRioToFillMetadata.Resolution = String.Format("{0} dpi", image.VerticalResolution);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Does the barcode reconition.
        /// </summary>
        /// <param name="FileFullPath">The file full path.</param>
        /// <returns></returns>
        public BarcodeResultItemCollection DoBarcodeRecognition(string FileFullPath)
        {

            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- DoBarcodeReconition ------------------------------------------------ " + DateTime.Now);
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------------------ File FileFullPath[" + FileFullPath + "] --------------------------- ");


            long barcodeCount = 0;
            int m_ImageID = 0;
            BarcodeResultItemCollection collection = new BarcodeResultItemCollection();

            try
            {
                //Open image
                var l_oSourceFileInfo = new FileInfo(FileFullPath);
                if (l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.BMP.szGetDescription())
                    || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.JPEG.szGetDescription())
                    || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.JPG.szGetDescription())
                    || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.TIF.szGetDescription())
                    || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.TIFF.szGetDescription())
                    || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.PNG.szGetDescription())
                    || l_oSourceFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.GIF.szGetDescription())
                    )
                {
                    m_ImageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(FileFullPath);
                }
                else if (l_oSourceFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.PDF.szGetDescription()))
                {
                    if (m_oGdPicturePDF.LoadFromFile(FileFullPath, true) == GdPictureStatus.OK)
                    {
                        m_oGdPicturePDF.SelectPage(1);
                        m_ImageID = m_oGdPicturePDF.RenderPageToGdPictureImage(200, false);
                    }
                }

                // Start reco
                m_oGdPictureImaging.Barcode1DReaderDoScan(m_ImageID, Barcode1DReaderScanMode.BestQuality);
                if (m_oGdPictureImaging.GetStat() == GdPictureStatus.OK)
                {
                    barcodeCount = m_oGdPictureImaging.Barcode1DReaderGetBarcodeCount();
                    if (barcodeCount > 0)
                    {
                        NetBay.Core.Log.LogManager.Instance().LogDebugFormat("- {0} barcode(s) found", barcodeCount.ToString());
                        for (int i = 1; i <= barcodeCount; i++)
                        {
                            string type = m_oGdPictureImaging.Barcode1DReaderGetBarcodeType(i).ToString();
                            string value = m_oGdPictureImaging.Barcode1DReaderGetBarcodeValue(i);

                            //Match barcode type between gdpicture and rio type
                            BarcodeType rioTYpe = (BarcodeType)Enum.Parse(typeof(BarcodeType), type, true);
                            collection.Add(new BarcodeResultItem(value, rioTYpe));

                            NetBay.Core.Log.LogManager.Instance().LogDebugFormat("- New Barcode recognized, type={0}, value:{1}", type, value);
                        }
                    }
                    else
                    {
                        NetBay.Core.Log.LogManager.Instance().LogDebug("- No barcode found");
                    }
                }
                m_oGdPictureImaging.Barcode1DReaderClear();
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN DoBarcodeReconition EXCEPTION: [" + ex.ToString() + "] " + DateTime.Now);
            }
            finally
            {
                //Release image
                if (m_ImageID > 0)
                {
                    m_oGdPictureImaging.ReleaseGdPictureImage(m_ImageID);
                }

                if (m_oGdPicturePDF != null)
                    m_oGdPicturePDF.CloseDocument();
            }

            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of DoBarcodeReconition ------------------------------------------------ " + DateTime.Now);

            return collection;
        }

        /// <summary>
        /// Does the conversion.
        /// </summary>
        /// <param name="p_sFile">The P_S file.</param>
        /// <param name="p_sPassword">The P_S password.</param>
        /// <param name="p_sFolder">The P_S folder.</param>
        /// <param name="p_iDpi">The p_i dpi.</param>
        /// <param name="p_sPagerange">The P_S pagerange.</param>
        /// <param name="p_oIType">Type of the p_o I.</param>
        public void DoConversion(string p_sFile, string p_sPassword, string p_sFolder, int p_iDpi, string p_sPagerange, ImageType p_oIType)
        {
            try
            {
                //// Setup the outputfolder
                Treatments.CheckDirectory(Path.GetDirectoryName(p_sFolder));
                var l_sFilename = p_sFolder;
                SavePdfPageToJpg(p_sFile, p_iDpi, l_sFilename);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("DoConversion---erreur lors du DoConversion-----------------Exception [" + ex.Message + "]");
                throw ex;
            }
        }


        /// <summary>
        /// Saves the PDF page to JPG.
        /// </summary>
        /// <param name="pdfFile">The PDF file.</param>
        /// <param name="dpi">The dpi.</param>
        /// <param name="jpgFileName">Name of the JPG file.</param>
        public void SavePdfPageToJpg(string pdfFile, int dpi, string jpgFileName)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            NetBay.Core.Log.LogManager.Instance().LogInfo("SaveJpgGdPicture CALLED --------------------------");
            int RasterizedPageID = 0;
            try
            {

                if (m_oGdPicturePDF.LoadFromFile(pdfFile, false) == GdPictureStatus.OK)
                {
                    m_oGdPicturePDF.SelectPage(1);
                    RasterizedPageID = m_oGdPicturePDF.RenderPageToGdPictureImage(dpi, true);

                    // If the file exits already, delete it. I.E. Overwrite it.
                    if (File.Exists(jpgFileName))
                        File.Delete(jpgFileName);

                    //Save format JPG
                    GdPicture.GdPictureStatus l_oStatus = m_oGdPictureImaging.SaveAsJPEG(RasterizedPageID, jpgFileName);
                    NetBay.Core.Log.LogManager.Instance().LogDebug("SaveJpgGdPicture - file saved with status: " + l_oStatus.ToString());
                }

                NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
                NetBay.Core.Log.LogManager.Instance().LogInfo("---SaveJpgGdPicture-----------------");
                NetBay.Core.Log.LogManager.Instance().LogInfo("END OF CALL ---------------------");

            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("SaveJpgGdPicture---erreur lors du SaveJpgGdPicture-----------------Exception [" + ex.Message + "]");
                throw ex;
            }
            finally
            {
                //Release image
                if (RasterizedPageID > 0)
                {
                    m_oGdPictureImaging.ReleaseGdPictureImage(RasterizedPageID);
                }

                if (m_oGdPicturePDF != null)
                    m_oGdPicturePDF.CloseDocument();

            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing,
        /// or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            _isInit = false;

            //release imaging
            this.m_oGdPictureImaging = null;

            //release pdf
            if (m_oGdPicturePDF != null)
                m_oGdPicturePDF.CloseDocument();
            this.m_oGdPicturePDF = null;
        }
        #endregion

        #region Private method


        /// <summary>
        /// Get the optimal size of the image
        /// </summary>
        /// <param name="p_iActuelWidth">The actual size of the image</param>
        /// <param name="p_iActuelHeigth">The actual heigth of the image</param>
        /// <param name="p_iMax">The maximum heigth or width accepted</param>
        /// <returns>The new optimal size</returns>
        private Size GetSizeImage(int p_iActuelWidth, int p_iActuelHeigth, int p_iMax)
        {
            var l_oSize = new Size(p_iActuelWidth, p_iActuelHeigth);

            if (p_iActuelWidth > p_iActuelHeigth)
            {
                var l_iRatio = float.Parse(p_iActuelWidth.ToString()) / float.Parse(p_iActuelHeigth.ToString());
                var l_iNewWidth = p_iMax * l_iRatio;

                l_oSize.Height = p_iMax;
                l_oSize.Width = Convert.ToInt32(l_iNewWidth);
            }
            else
            {
                var l_iRatio = float.Parse(p_iActuelHeigth.ToString()) / float.Parse(p_iActuelWidth.ToString());
                var l_iNewHeigth = p_iMax * l_iRatio;

                l_oSize.Width = p_iMax;
                l_oSize.Height = Convert.ToInt32(l_iNewHeigth);
            }

            return l_oSize;
        }

        /// <summary>
        /// Resize the image to a new Width and heigth
        /// </summary>
        /// <param name="p_sOriginalFile">The original filename full path</param>
        /// <param name="p_sNewFile">The destination filename full path</param>
        /// <param name="p_iWidth">The new width of the image</param>
        /// <param name="p_iHeigth">The new hekgth of the image</param>
        public void ResizeImage(string p_sOriginalFile, string p_sNewFile, int p_iWidth, int p_iHeigth)
        {
            Image l_oFullsizeImage = null;
            Image l_oNewImage = null;

            try
            {
                l_oFullsizeImage = Image.FromFile(p_sOriginalFile);

                // Prevent using images internal thumbnail
                l_oFullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                l_oFullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);

                l_oNewImage = l_oFullsizeImage.GetThumbnailImage(p_iWidth, p_iHeigth, null, IntPtr.Zero);

                // Clear handle to original file so that we can overwrite it if necessary
                l_oFullsizeImage.Dispose();

                // Save resized picture
                l_oNewImage.Save(p_sNewFile);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("ResizeImage---------------Exception [" + ex.ToString() + "]");
            }
            finally
            {
                if (l_oFullsizeImage != null)
                    l_oFullsizeImage.Dispose();
                if (l_oNewImage != null)
                    l_oNewImage.Dispose();
            }
        }

        /// <summary>
        /// Exrtact a thumbnail from an image
        /// </summary>
        /// <param name="p_lSourceFileInfo">Image source file FileInfo</param>
        /// <param name="p_sDestinationFileFullPath"></param>
        private void CreateImageThumbNail(FileSystemInfo p_lSourceFileInfo, string p_sDestinationFileFullPath)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreateImageThumbNail ------------------------------------------------ " + DateTime.Now);

            if (p_lSourceFileInfo == null) throw new ArgumentNullException("p_lSourceFileInfo", "Exception in CreateImageThumbNail : p_lSourceFileInfo is null");

            var l_sExtension = Path.GetExtension(p_lSourceFileInfo.FullName);
            int m_iImageID = 0;

            try
            {

                if (l_sExtension != null)
                {

                    if (l_sExtension.ToLower() == Constant.ImageFileFormat.JPEG.szGetDescription()
                         || l_sExtension.ToLower() == Constant.ImageFileFormat.JPG.szGetDescription())
                    {
                        ResizeImage(p_lSourceFileInfo.FullName, p_sDestinationFileFullPath,
                                    int.Parse(ConfigurationManager.AppSettings.Get("ImageWidth")),
                                    int.Parse(ConfigurationManager.AppSettings.Get("ImageHeigth")), false);
                    }
                    else
                    {

                        int l_iHeigth = 0;
                        int l_iWidth = 0;

                        m_iImageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(p_lSourceFileInfo.FullName);
                        m_oGdPictureImaging.SaveAsJPEG(m_iImageID, p_sDestinationFileFullPath);

                        l_iHeigth = m_oGdPictureImaging.GetHeight(m_iImageID);
                        l_iWidth = m_oGdPictureImaging.GetWidth(m_iImageID);

                        if (l_iHeigth > int.Parse(ConfigurationManager.AppSettings.Get("ImageHeigth")) ||
                             l_iWidth > int.Parse(ConfigurationManager.AppSettings.Get("ImageWidth")))
                        {
                            ResizeImage(
                                p_sDestinationFileFullPath,
                                p_sDestinationFileFullPath,
                                int.Parse(ConfigurationManager.AppSettings.Get("ImageWidth")),
                                int.Parse(ConfigurationManager.AppSettings.Get("ImageHeigth"))
                                );
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("CreateImageThumbNail---erreur lors du CreateImageThumbNail-----------------Exception [" + ex.Message + "]");
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\misc.jpg"), p_sDestinationFileFullPath, true);
            }
            finally
            {
                if (m_iImageID > 0)
                    m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
            }

            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreateImageThumbNail ------------------------------------------------ " + DateTime.Now);
        }

        /// <summary>
        /// Extract a thumbnail from a video
        /// </summary>
        /// <param name="p_sDestinationFileFullPath">Destination full Path</param>
        private void CreateVideoThumbNail(string p_sDestinationFileFullPath)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreateVideoThumbNail ------------------------------------------------ " + DateTime.Now);

            try
            {
                var l_sUri = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones");
                File.Copy(Path.Combine(l_sUri, "video.jpg"), p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogInfo("--------------------------------- New Thumb created [" + p_sDestinationFileFullPath + "] --------------------------- ");
            }
            catch (Exception ex)
            {
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\video.jpg"), p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN LaunchVideoThumbExtract EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreateVideoThumbNail ------------------------------------------------ " + DateTime.Now);
        }

        /// <summary>
        /// Extract a thumbnail from a PDF file
        /// </summary>
        /// <param name="p_lSourceFileInfo">Source file FileInfo</param>
        /// <param name="p_sDestinationFileFullPath"></param>
        private void CreatePdfThumbNail(FileSystemInfo p_lSourceFileInfo, string p_sDestinationFileFullPath)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreatePdfThumbNail ------------------------------------------------ " + DateTime.Now);
            try
            {
                //Create instance for the PDF reader
                var l_oPdfReader = new PdfReader(p_lSourceFileInfo.FullName);
                //read it's pagecount
                var l_iPageCount = l_oPdfReader.NumberOfPages;
                var l_bDoUseSolidFramework = true;
                //close the file
                var l_sFilenameFullPath = string.Empty;
                var l_sOutputdirectory = string.Empty;
                if (l_iPageCount > 1)
                {
                    // lets get the first page of the pdf to create the thumbnail
                    l_sOutputdirectory = Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"), Guid.NewGuid().ToString("N"));
                    CheckDirectory(l_sOutputdirectory);
                    l_sFilenameFullPath = Path.Combine(l_sOutputdirectory, "first_page" + Constant.DocumentFileFormat.PDF.szGetDescription());

                    try
                    {
                        ExtractPdfPage(l_oPdfReader, 1, l_sFilenameFullPath, p_lSourceFileInfo.FullName);
                    }
                    catch
                    {
                        l_oPdfReader.Close();
                        //In this case Itextsharp did not manage to extract the page of the multipage pdf file. So we will use soldiframework to do it.
                        //we try not using solidfrfaamework for the pdf file because the process to convert is long for big pdf file.
                        //var l_oPDFtoImagecatch = new Treatments();
                        try
                        {
                            DoConversion(p_lSourceFileInfo.FullName, null, p_sDestinationFileFullPath, int.Parse(ConfigurationManager.AppSettings.Get("DoConversionHigh")), "0", Treatments.ImageType.Jpg);
                        }
                        catch (Exception)
                        {
                            DoConversion(p_lSourceFileInfo.FullName, null, p_sDestinationFileFullPath, int.Parse(ConfigurationManager.AppSettings.Get("DoConversionLow")), "0", Treatments.ImageType.Jpg);
                        }

                       // l_oPDFtoImagecatch = null;
                        l_bDoUseSolidFramework = false;
                    }

                    if (File.Exists(l_sFilenameFullPath))
                    {
                        p_lSourceFileInfo = new FileInfo(l_sFilenameFullPath);
                    }
                }

                l_oPdfReader.Close();


                if (l_bDoUseSolidFramework)
                {
                    DoConversion(p_lSourceFileInfo.FullName, null, p_sDestinationFileFullPath,
                                               int.Parse(ConfigurationManager.AppSettings.Get("DoConversionLow")), "0",
                                               Treatments.ImageType.Jpg);
                }

                ResizeImage(
                            p_sDestinationFileFullPath,
                            p_sDestinationFileFullPath,
                            int.Parse(ConfigurationManager.AppSettings.Get("ImageWidth")),
                            int.Parse(ConfigurationManager.AppSettings.Get("ImageHeigth"))
                            );


                if ((l_iPageCount > 1) && !l_sOutputdirectory.Equals(string.Empty))
                {
                    DeleteDirectory(Path.GetDirectoryName(p_lSourceFileInfo.FullName));
                }

                if (!l_sFilenameFullPath.Equals(string.Empty) && Directory.Exists(Path.GetDirectoryName(l_sFilenameFullPath)))
                    DeleteDirectory(Path.GetDirectoryName(l_sFilenameFullPath));
            }
            catch (Exception ex)
            {
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\pdf.jpg"),
                    p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CreatePdfThumbNail EXCEPTION: [" + ex.StackTrace + "] " + DateTime.Now);
            }
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreatePdfThumbNail ------------------------------------------------ " + DateTime.Now);



        }

        /// <summary>
        /// Create a XLS thumbnail
        /// </summary>
        /// <param name="p_lSourceFileInfo">Source file FileInfo</param>
        /// <param name="p_sDestinationFileFullPath"></param>
        private void CreateExcelThumbNail(FileSystemInfo p_lSourceFileInfo, string p_sDestinationFileFullPath)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreateExcelThumbNail ------------------------------------------------ " + DateTime.Now);

            #region Aspose Licencing
            var cellLicence = new Aspose.Cells.License();
            cellLicence.SetLicense("Aspose.Total.lic");
            #endregion

            #region Aspose 9.2 code version
            //var l_oWorkbook = new Workbook(p_lSourceFileInfo.FullName);
            #endregion

            try
            {

                var l_oWorkbook = new Workbook(p_lSourceFileInfo.FullName);
                //l_oWorkbook.Open(p_lSourceFileInfo.FullName);

                var l_oImgOptions = new ImageOrPrintOptions
                {
                    
                    ImageFormat = ImageFormat.Jpeg,
                    IsImageFitToPage = true,
                    OnePagePerSheet = false
                };


                var l_oSheet = l_oWorkbook.Worksheets[0];
                l_oSheet.IsGridlinesVisible = true;

                //Setting the orientation to Portrait
                l_oSheet.PageSetup.Orientation = PageOrientationType.Landscape;

                //Setting the paper size to Tabloid
                l_oSheet.PageSetup.PaperSize = PaperSizeType.PaperTabloid;

                //Setting the print quality of the worksheet to 1200 dpi
                l_oSheet.PageSetup.PrintQuality = 1200;
                var l_oSheetRender = new SheetRender(l_oSheet, l_oImgOptions);

                //Convert worksheet to image.
                l_oSheetRender.ToImage(0, p_sDestinationFileFullPath);
            }
            catch (Exception ex)
            {
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\excel.jpg"), p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CreateExcelThumbNail EXCEPTION: [" + ex.StackTrace + "] " + DateTime.Now);
            }
            NetBay.Core.Log.LogManager.Instance().LogInfo("--------------------------------- New Thumb created [" + p_sDestinationFileFullPath + "] --------------------------- ");
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreateExcelThumbNail ------------------------------------------------ " + DateTime.Now);
        }

        /// <summary>
        /// Create a WORD thumbnail
        /// </summary>
        /// <param name="p_lSourceFileInfo">Source file FileInfo</param>
        /// <param name="p_sDestinationFileFullPath">Destination full Path</param>
        private void CreateWordThumbNail(FileSystemInfo p_lSourceFileInfo, string p_sDestinationFileFullPath)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreateWordThumbNail ------------------------------------------------ " + DateTime.Now);

            try
            {
                #region Aspose Licencing
                var wordLicence = new Aspose.Words.License();
                wordLicence.SetLicense("Aspose.Total.lic");
                #endregion

                #region Aspose 9.2 code version
                //var l_oWordDocument = new Aspose.Words.Document(p_lSourceFileInfo.FullName);

                //var l_oImageOptions = new ImageSaveOptions(Aspose.Words.SaveFormat.Jpeg)
                //                          {
                //                              JpegQuality = 100,
                //                              Resolution = 100,
                //                              PageIndex = 0
                //                          };
                //l_oWordDocument.Save(Path.Combine(p_sDestinationFullPath, p_lSourceFileInfo.Name + Constant.ImageFileFormat.JPG.szGetDescription()), l_oImageOptions);
                #endregion

                var l_oWordDocument = new Aspose.Words.Document(p_lSourceFileInfo.FullName);
                var l_oImageOptions = new ImageOptions { JpegQuality = int.Parse(ConfigurationManager.AppSettings.Get("ImageQuality")), Resolution = int.Parse(ConfigurationManager.AppSettings.Get("ImageResolution")) };
                l_oWordDocument.SaveToImage(0, 1, p_sDestinationFileFullPath, l_oImageOptions);

                NetBay.Core.Log.LogManager.Instance().LogInfo("--------------------------------- New Thumb created [" + p_sDestinationFileFullPath + "] --------------------------- ");

                l_oWordDocument = null;
                l_oImageOptions = null;
            }
            catch (Exception ex)
            {
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\word.jpg"), p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CreateWordThumbNail EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreateWordThumbNail ------------------------------------------------ " + DateTime.Now);
        }

        /// <summary>
        /// Create a Powerpoint thumbnail
        /// </summary>
        /// <param name="p_lSourceFileInfo">Source file FileInfo</param>
        /// <param name="p_sDestinationFileFullPath"></param>
        private void CreatePowerPointThumbNail(FileSystemInfo p_lSourceFileInfo, string p_sDestinationFileFullPath)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreatePowerPointThumbNail ------------------------------------------------ " + DateTime.Now);

            try
            {
                #region Aspose Licencing
                var slideLicence = new Aspose.Slides.License();
                slideLicence.SetLicense("Aspose.Total.lic");
                #endregion

                var l_oPresentation = new Presentation(p_lSourceFileInfo.FullName);
                //Accessing a slide using its slide position
                var slide = l_oPresentation.GetSlideByPosition(1);
                var l_oImage = slide.GetThumbnail(new Size(int.Parse(ConfigurationManager.AppSettings.Get("ImageWidth")), int.Parse(ConfigurationManager.AppSettings.Get("ImageHeigth"))));
                l_oImage.Save(p_sDestinationFileFullPath);
                l_oImage.Dispose();
            }
            catch (Exception ex)
            {
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\powerPoint.jpg"), p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CreatePowerPointThumbNail EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreatePowerPointThumbNail ------------------------------------------------ " + DateTime.Now);
        }

        /// <summary>
        /// Create a Powerpoint thumbnail
        /// </summary>
        /// <param name="p_lSourceFileInfo">Source file FileInfo</param>
        /// <param name="p_sDestinationFileFullPath"></param>
        private void CreatePowerPointXThumbNail(FileSystemInfo p_lSourceFileInfo, string p_sDestinationFileFullPath)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreatePowerPointXThumbNail ------------------------------------------------ " + DateTime.Now);

            try
            {
                #region Aspose Licencing
                var slideLicence = new Aspose.Slides.License();
                slideLicence.SetLicense("Aspose.Total.lic");
                #endregion

                var l_oPresentation = new PresentationEx(p_lSourceFileInfo.FullName);
                //Accessing a slide using its slide position
                var slide = l_oPresentation.GetSlideById(l_oPresentation.Slides[0].SlideId);
                var l_oImage = slide.GetThumbnail(1, 1);
                l_oImage.Save(p_sDestinationFileFullPath);
                l_oImage.Dispose();
            }
            catch (Exception ex)
            {
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\powerPoint.jpg"), p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CreatePowerPointXThumbNail EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreatePowerPointXThumbNail ------------------------------------------------ " + DateTime.Now);
        }

        /// <summary>
        /// Create a Powerpoint thumbnail
        /// </summary>
        /// <param name="p_sDestinationFileFullPath"></param>
        private void CreateTxtThumbNail(string p_sDestinationFileFullPath)
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreateTxtThumbNail ------------------------------------------------ " + DateTime.Now);

            try
            {
                var l_sUriSourceIcon = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\Txt.jpg");
                File.Copy(l_sUriSourceIcon, p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogInfo("--------------------------------- New Thumb created [" + p_sDestinationFileFullPath + "] --------------------------- ");
            }
            catch (Exception ex)
            {
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\Txt.jpg"), p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CreateTxtThumbNail EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreateTxtThumbNail ------------------------------------------------ " + DateTime.Now);
        }

        /// <summary>
        /// Create a Misc File thumbnail
        /// </summary>
        /// <param name="p_sDestinationFileFullPath"></param>
        private void CreateMiscFileThumbNail(string p_sDestinationFileFullPath, string p_sFileExtension = "misc")
        {
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- CreateMiscFileThumbNail ------------------------------------------------ " + DateTime.Now);

            try
            {
                var l_sUriSourceIcon = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\" + p_sFileExtension + ".jpg");
                File.Copy(l_sUriSourceIcon, p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogInfo("--------------------------------- New Thumb created [" + p_sDestinationFileFullPath + "] --------------------------- ");
            }
            catch (Exception ex)
            {
                File.Copy(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\misc.jpg"), p_sDestinationFileFullPath, true);
                NetBay.Core.Log.LogManager.Instance().LogError("------------- EXCEPTION IN CreateMiscFileThumbNail EXCEPTION: [" + ex.Message + "] " + DateTime.Now);
            }
            NetBay.Core.Log.LogManager.Instance().LogInfo("------------- End of CreateMiscFileThumbNail ------------------------------------------------ " + DateTime.Now);
        }

        
               
        #endregion
    }
}